package org.liurb.springboot.starter.common.validator;

import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.liurb.springboot.starter.common.annotation.EnumTypeAnnotation;
import org.liurb.springboot.starter.common.utils.TypeEnumUtil;


/**
 * 枚举注解校验
 *
 * 使用时将注解加在dto的字段中
 *
 * @Author Liurb
 * @Date 2022/11/28
 */
public class EnumTypeValidator implements ConstraintValidator<EnumTypeAnnotation, Integer> {

    EnumTypeAnnotation enumTypeAnnotation;

    @Override
    public void initialize(EnumTypeAnnotation constraintAnnotation) {
        this.enumTypeAnnotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {

        if (value == null) {
            return true;
        }

        //获取枚举class
        String enumName = TypeEnumUtil.getEnumNameByType(enumTypeAnnotation.clazz(), value);
        if (StrUtil.isBlank(enumName)) {
            return false;
        }

        return true;
    }
}
